package com.ischoolbar.programmer.controller.admin;

import com.github.pagehelper.util.StringUtil;
import com.ischoolbar.programmer.entity.admin.Role;
import com.ischoolbar.programmer.entity.admin.User;
import com.ischoolbar.programmer.page.admin.Page;
import com.ischoolbar.programmer.service.admin.IRoleService;
import com.ischoolbar.programmer.service.admin.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    IUserService userService;

    @Autowired
    IRoleService roleService;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model) {
        Map<String, Object> queryMap = new HashMap<>();
        List<Role> roleList = roleService.findRoleList(queryMap);
        model.addAttribute("roleList", roleList);
        return "user/list";
    }

    @RequestMapping(value = "/get_list", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> get_list(Page page,
                                        @RequestParam(value = "username", required = false,  defaultValue = "") String username,
                                        @RequestParam(value = "roleId", required = false) Integer roleId,
                                        @RequestParam(value = "sex", required = false) Integer sex) {

        Map<String, Object> queryMap = new HashMap<>();
        Map<String, Object> ret = new HashMap<>();

        queryMap.put("username", username);
        queryMap.put("roleId", roleId);
        queryMap.put("sex", sex);

        queryMap.put("offset", page.getOffset());
        queryMap.put("pageSize", page.getRows());

        List<User> allUser = userService.findAllUser(queryMap);

        ret.put("rows", allUser);
        ret.put("total", userService.getTotalCount());

        return ret;
    }

    /*
    * 添加
    * */
    @RequestMapping(value = "/add_user", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> add(User user) {
        Map<String, Object> ret = new HashMap<>();
        if (user == null) {
            ret.put("type", "error");
            ret.put("msg", "请填写正确的用户信息");
            return ret;
        }

        if (StringUtil.isEmpty(user.getUsername())) {
            ret.put("type", "error");
            ret.put("msg", "用户名不能为空");
            return ret;
        }

        if (StringUtil.isEmpty(user.getPassword())) {
            ret.put("type", "error");
            ret.put("msg", "密码不能为空");
            return ret;
        }

        if (StringUtil.isEmpty(user.getRoleId().toString())) {
            ret.put("type", "error");
            ret.put("msg", "所属角色不能为空");
            return ret;
        }

        if (userIsExist(user.getUsername())) {
            ret.put("type", "error");
            ret.put("msg", "用户名已存在, 请更换一个用户名");
            return ret;
        }

        int i = userService.add(user);
        if (i <= 0) {
            ret.put("type", "error");
            ret.put("msg", "用户添加失败");
            return ret;
        }

        ret.put("type", "success");
        ret.put("msg", "用户添加成功");

        return ret;
    }

    /*
    * 判断用户名是否存在
    * */
    public Boolean userIsExist(String username) {
        User findByUsername = userService.findUserByUsername(username);
        if (findByUsername == null) {
            return false;
        }
        if (!username.equals(findByUsername.getUsername())) {
            return false;
        }

        return true;

    }

    /*
    * 修改用户信息
    * */
    @RequestMapping(value = "/edit_user", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> edit_user(User user) {
        Map<String, Object> ret = new HashMap<>();

        if (user == null) {
            ret.put("type", "error");
            ret.put("msg", "请填写正确的用户信息");
            return ret;
        }

        if (StringUtil.isEmpty(user.getUsername())) {
            ret.put("type", "error");
            ret.put("msg", "用户名不能为空");
            return ret;
        }

//        if (StringUtil.isEmpty(user.getPassword())) {
//            ret.put("type", "error");
//            ret.put("msg", "密码不能为空");
//            return ret;
//        }

        if (StringUtil.isEmpty(user.getId().toString())) {
            ret.put("type", "error");
            ret.put("msg", "所属角色不能为空");
            return ret;
        }

        if (userIsExist(user.getUsername())) {
            ret.put("type", "error");
            ret.put("msg", "用户名已存在, 请更换一个用户名");
            return ret;
        }

        int i = userService.edit(user);
        if (i <= 0) {
            ret.put("type", "error");
            ret.put("msg", "用户修改失败");
            return ret;
        }

        ret.put("type", "success");
        ret.put("msg", "用户修改成功");

        return ret;
    }

    /*
    * 批量删除用户
    * */
    @RequestMapping(value = "/delete_user", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> delete_user(@RequestParam(value = "ids", required = true) String ids) {
        Map<String, Object> ret = new HashMap<>();
        if (StringUtil.isEmpty(ids)) {
            ret.put("type", "error");
            ret.put("msg", "请选择要删除的角色");
            return ret;
        }

        if (ids.contains(",")) {
            ids = ids.substring(0, ids.length() - 1);
        }

        userService.delete(ids);
        ret.put("type", "success");
        ret.put("msg", "删除成功");
        return ret;
    }


    /*
    * 图像上传
    * */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upload(MultipartFile photo, HttpServletRequest request) {
        Map<String, Object> ret = new HashMap<>();
        if (photo == null) {
            ret.put("type", "error");
            ret.put("msg", "请选择要上传的图像");
            return ret;
        }

        if (photo.getSize() > (1024 * 1024 * 1024)) {
            ret.put("type", "error");
            ret.put("msg", "上传文件大小不能大于10MB");
            return ret;
        }

        // 获取上传文件的后缀
        String originalFileName = photo.getOriginalFilename();
        String suffix = originalFileName.substring(originalFileName.lastIndexOf(".") + 1, originalFileName.length());
        if (!"jpg,jpeg,gif,png".contains(suffix)) {
            ret.put("type", "error");
            ret.put("msg", "上传的文件格式只支持jpg,jpeg,gif,png格式");
            return ret;
        }


        // 获取项目路径
        String savePath = request.getServletContext().getRealPath("/") + "/resources/upload/";
        File uploadDir = new File(savePath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        String filename = new Date().getTime() + "." + suffix;

        try {
            photo.transferTo(new File(savePath + filename));
        } catch (IOException e) {
            ret.put("type", "error");
            ret.put("msg", "图像上传失败");
            e.printStackTrace();
            return ret;
        }

        ret.put("type", "success");
        ret.put("msg", "上传成功");
        ret.put("avater", "http:localhost:8080" + request.getServletContext().getContextPath() + "/" +  filename);
        return ret;
    }
}
